package encryption

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"math/big"
	"net"
	"os"
	"time"
)

const (
	// tlsCrtSecretKey is the key in the secret where the TLS certificate is stored.
	tlsCrtSecretKey = "tls.crt"
	// tlsKeySecretKey is the key in the secret where the TLS private key is stored.
	tlsKeySecretKey = "tls.key"
)

// pemBlockForKey returns a PEM block with a private key.
func pemBlockForKey(prov interface{}) *pem.Block {
	switch k := prov.(type) {
	case *ecdsa.PrivateKey:
		b, err := x509.MarshalECPrivateKey(k)
		if err != nil {
			os.Exit(2)
		}
		return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
	default:
		return nil
	}
}

// generate generates a self-signed certificate and private key.
func generate() ([]byte, crypto.PrivateKey, error) {
	hosts := []string{"localhost"}
	var err error
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to generate private key: %v", err)
	}
	notBefore := time.Now()
	notAfter := notBefore.Add(time.Hour * 24 * 365)
	serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to generate serial number: %v", err)
	}
	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"Holly Co"},
		},
		NotBefore:             notBefore,
		NotAfter:              notAfter,
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	for _, h := range hosts {
		if ip := net.ParseIP(h); ip != nil {
			template.IPAddresses = append(template.IPAddresses, ip)
		} else {
			template.DNSNames = append(template.DNSNames, h)
		}
	}

	certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to create certificate: %v", err)
	}
	return certBytes, key, nil
}

// generatePem generates a self-signed certificate and private key in PEM format.
func generatePem() ([]byte, []byte, error) {
	certBytes, key, err := generate()
	if err != nil {
		return nil, nil, err
	}
	certPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
	keyPem := pem.EncodeToMemory(pemBlockForKey(key))
	return certPem, keyPem, nil
}

// GenerateX509KeyPair generates a self-signed certificate and private key in X509 format.
func GenerateX509KeyPair() (*tls.Certificate, error) {
	certPem, keyPem, err := generatePem()
	if err != nil {
		return nil, err
	}
	cert, err := tls.X509KeyPair(certPem, keyPem)
	if err != nil {
		return nil, err
	}
	return &cert, nil
}

// GenerateX509KeyPairTLSConfig generates a self-signed certificate and private key in X509 format and returns a TLS config.
func GenerateX509KeyPairTLSConfig(tlsMinVersion uint16) (*tls.Config, error) {
	cer, err := GenerateX509KeyPair()
	if err != nil {
		return nil, err
	}
	return &tls.Config{
		Certificates:       []tls.Certificate{*cer},
		MinVersion:         tlsMinVersion,
		InsecureSkipVerify: true,
	}, nil
}
